package com.ifar.audiosdk.model.login.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.ifar.audiosdk.R
import com.ifar.audiosdk.base.IfarBaseViewModel
import com.ifar.audiosdk.common.IfarBaseResponse
import com.ifar.audiosdk.common.IfarConfig
import com.ifar.audiosdk.api.ApiRepository
import com.ifar.audiosdk.model.login.model.LoginEntity
import com.ifar.audiosdk.model.login.model.LoginFormState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LoginViewModel : IfarBaseViewModel() {
    private val repository by lazy { ApiRepository() }
    val apiError: MutableLiveData<String> = MutableLiveData()
    val apiLoginSuccess: MutableLiveData<LoginEntity> = MutableLiveData()

    private val _loginForm = MutableLiveData<LoginFormState>()
    val loginFormState: LiveData<LoginFormState> = _loginForm

    /**
     * 登录
     */
    fun login(username: String, password: String) {
        launch {
            val resp = withContext(Dispatchers.IO) { repository.login(username, password) }
            executeResponse(resp, {
                saveUserInfo(resp, username, password)
                apiLoginSuccess.value = resp.data
            }, {
                apiError.value = resp.msg
            })
        }
    }

    /**
     * 成功登陆保存用户信息
     */
    private fun saveUserInfo(
        resp: IfarBaseResponse<LoginEntity>,
        username: String,
        password: String
    ) {
        IfarConfig.id = resp.data.id
        IfarConfig.token = resp.data.token
        IfarConfig.name = username
        IfarConfig.password = password
        IfarConfig.nike_name = resp.data.nickname
        IfarConfig.group_name = resp.data.group_name
        IfarConfig.ws_port = resp.data.ws_port
        IfarConfig.avatar = resp.data.avatar
        IfarConfig.phone = resp.data.phone
        IfarConfig.email = resp.data.email
        IfarConfig.permission = resp.data.permission
        IfarConfig.company_id = resp.data.company_id
        IfarConfig.is_sign_in = resp.data.is_signin
    }

    fun loginDataChanged(username: String, password: String) {
        if (username.isEmpty()) {
            _loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
        } else if (!isPasswordValid(password)) {
            _loginForm.value = LoginFormState(passwordError = R.string.invalid_password)
        } else {
            _loginForm.value = LoginFormState(isDataValid = true)
        }
    }

    private fun isPasswordValid(password: String): Boolean {
        return password.length > 5
    }
}